package SymbolTable.OrderSymbolTable;

/*
    用链表实现有序符号表，符号表（存键值对）
    根据 key 来排序，但是 key 是对象类型，所以需要实现了 Comparable 接口的类才行
 */
public class OrderSymbolTable<K extends Comparable<K>, V> {

    private class Node<K, V> {
        K key;
        V value;
        Node<K, V> next;

        public Node(K key, V value, Node<K, V> next) {
            this.key = key;
            this.value = value;
            this.next = next;
        }

    }

    private Node<K, V> head;
    private int N;

    public OrderSymbolTable() {
        head = new Node<>(null, null, null);
        N = 0;
    }

    public int size() {
        return N;
    }

    public V get(K key) {
        Node<K, V> current = head;
        while (current.next != null) {
            current = current.next;
            if (current.key.equals(key)) {
                return current.value;
            }
        }
        return null;
    }

    //由 put 方法实现有序
    public void put(K key, V value) {
        Node<K,V> current = head.next;
        Node<K,V> pre = head;
        while(current!=null && key.compareTo(current.key)>0){
            //要插入的 key 大于当前节点的 key，继续后移
            pre=current;
            current= current.next;
        }
        //key 值已存在，直接替换value
        if(current!=null && key.compareTo(current.key)==0){
            current.value=value;
            return;
        }
        //key 值不存在，新增节点
        Node<K, V> node = new Node<>(key, value, current);
        pre.next=node;
        N++;
    }

    public V delete(K key) {
        Node<K, V> n = head;
        while (n.next != null) {
            if (n.next.key.equals(key)) {
                Node<K, V> node = n.next;
                n.next = n.next.next;
                N--;
                return node.value;
            }
            n = n.next;
        }
        return null;
    }
}
